package com.nari.ncps.screen.controller.emergency;

import com.nari.ncps.screen.common.constant.Mn;
import com.nari.ncps.screen.common.constant.ModuleTemplateName;
import com.nari.ncps.screen.common.enums.ModuleProductEnum;
import com.nari.ncps.screen.common.pojo.ApiResponse;
import com.nari.ncps.screen.service.ImportFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * <p>
 * 火电 前端控制器
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Tag(name = "应急-火电产业", description = "火电产业")
@RestController
@RequestMapping("/electric-emerg")
public class EmergElectricController {


    @Value("${excelFilePath}")
    private String excelFilePath;

    @Autowired
    private ImportFileService importFileService;


    /**
     * 铝业模版下载接口
     * @param response HttpServletResponse
     * @throws Exception 异常信息
     */
    @Operation(summary = "火电模版下载", description = "火电模版下载")
    @GetMapping("/download")
    public void downloadExcelTemplate(HttpServletResponse response) throws Exception {

        String templateFilePath = excelFilePath + ModuleTemplateName.ELECTRIC_TEMPLATE_NAME;
        OutputStream os;
        try (InputStream inputStream = Files.newInputStream(Paths.get(templateFilePath))) {
            String filename = ModuleTemplateName.ELECTRIC_TEMPLATE_NAME;

            // 修复方案：正确编码文件名
            String encodedFilename = URLEncoder.encode(filename, "UTF-8")
                    .replaceAll("\\+", "%20"); // 将 + 替换为 %20

            // 设置 Content-Disposition 头
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + encodedFilename + "\"");

            // 对于现代浏览器，也可以添加 filename* 参数
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + encodedFilename + "\"; " +
                            "filename*=UTF-8''" + encodedFilename);

            // 设置正确的 Content-Type
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");

            os = response.getOutputStream();
            int len;
            byte[] b = new byte[Mn.M_1024_N];
            while ((len = inputStream.read(b, 0, b.length)) != -1) {
                os.write(b, 0, len);
            }
            os.flush();
        }
    }


    /**
     * 火电模版导入
     * @param file 上传的文件
     * @return ApiResponse<ImportMsgVoResp> 操作结果信息
     * @throws Exception 异常信息
     */
    @Operation(summary = "火电模版导入", description = "火电模版导入")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<Object> reportUpload(
            @Parameter(description = "文件参数", required = true)
            @RequestParam(value="file") MultipartFile file) throws Exception {

        if(file.isEmpty()){
            return ApiResponse.failed("文件不存在");
        }
        if(!Objects.requireNonNull(file.getOriginalFilename()).contains(".xlsx")) {
            return ApiResponse.failed("文件类型不匹配,上传.xlsx类型的文件");
        }
        return importFileService.standardUpload(file, ModuleProductEnum.ELECTRIC.getId());
    }


}
